//
//  USAddMemorialDayController.m
//  us
//
//  Created by karry on 2025/4/27.
//

#import "USAddMemorialDayController.h"
#import "USMemorialDayView.h"
#import "USColorPickerView.h"
#import "IQKeyboardManager.h"
#import "USMemorialChangeStickerCell.h"
#import "USStickerPickerView.h"
#import "USDateAlertView.h"
@interface USAddMemorialDayController ()<UITableViewDataSource,UITableViewDelegate,USStickerPickerViewDelegate>

@property (nonatomic,strong) USMemorialDayView *dayView;

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) NSArray <DTItem *>*list;

@property (nonatomic,strong) NSMutableArray<NSString *> *vividMacaronColors;

@property (nonatomic,strong) USStickerPickerView *stickerView;

@end

@implementation USAddMemorialDayController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.prefersLargeTitles = NO;
    [IQKeyboardManager sharedManager].enable = YES;
    IQKeyboardManager.sharedManager.enableAutoToolbar = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"添加新日子";
    
    self.navigationItem.rightBarButtonItem  = self.doneItem;


    if (!self.dayModel) {
        self.dayModel = [USMemorialDayModel new];
        self.dayModel.anniversaryDate = [NSString stringWithFormat:@"%li",(NSInteger)[[NSDate now] timeIntervalSince1970]];
             
        if (self.vividMacaronColors.count > 0) {
            self.dayModel.color = self.vividMacaronColors.firstObject;
        }
    }
    RAC(self.doneItem, enabled) = [RACObserve(self.dayModel, anniversaryName) map:^id _Nullable(NSString *text) {
        return @(text.length > 0);
    }];
 
    [self setupData];
    [self setupView];
    
}

- (void)setupData{
    
    DTItem *g_item0 = [DTItem itemWithTitle:@"" image:nil tag:0 identifier:@"g0" handle:nil];
    g_item0.items = @[
        [DTItem itemWithTitle:@"修改贴纸" image:[UIImage imageNamed:@"ic_ds_0"] tag:0 identifier:@"modifySticker" handle:nil]
    ];

    DTItem *g_item1 = [DTItem itemWithTitle:@"" image:nil tag:1 identifier:@"g1" handle:nil];
    NSMutableArray *items1Arr = [NSMutableArray arrayWithArray:@[
        [DTItem itemWithTitle:@"纪念日名称" image:[UIImage imageNamed:@"ic_ds_1"] tag:0 identifier:@"memorialName" handle:nil],
        [DTItem itemWithTitle:@"日期" image:[UIImage imageNamed:@"ic_ds_2"] tag:0 identifier:@"date" handle:nil],
        [DTItem itemWithTitle:@"包含起始日" image:[UIImage imageNamed:@"ic_ds_3"] tag:0 identifier:@"includeStartDate" handle:nil]
    ]];
    if (!self.dayModel.togetherFlag) {
        [items1Arr addObject:[DTItem itemWithTitle:@"每年重复" image:[UIImage imageNamed:@"ic_ds_4"] tag:0 identifier:@"repeatYearly" handle:nil]];
    }
    g_item1.items = items1Arr;

    DTItem *g_item2 = [DTItem itemWithTitle:@"" image:nil tag:2 identifier:@"g2" handle:nil];
    g_item2.items = @[
        [DTItem itemWithTitle:@"在首页显示" image:[UIImage imageNamed:@"ic_ds_5"] tag:0 identifier:@"pinTop" handle:nil]
    ];

    self.list = @[g_item0, g_item1, g_item2];

}


- (void)setupView{
    
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 160)];
    [self.view addSubview:header];
    
    USMemorialDayView *dayView = [[USMemorialDayView alloc]initWithFrame:CGRectMake(0, 0, 140, 160)];
    _dayView = dayView;
    [header addSubview:dayView];
    
    [header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.height.mas_equalTo(160 + 24 * 2);
    }];
    
    [dayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(header);
        make.width.mas_equalTo(174);
        make.height.mas_equalTo(178);
    }];
    
    dayView.dayModel = self.dayModel;

    UIView *pickerHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 22 + 16)];
    
    USColorPickerView *colorPickerView = [[USColorPickerView alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 22)];
    @weakify(self)
    colorPickerView.colorSelectedBlock = ^(UIColor * _Nonnull color) {
        @strongify(self)
        self.dayModel.color = color.jk_HEXString;
        self.dayView.dayModel = self.dayModel;
        [self.tableView reloadData];
    };
    [colorPickerView setColorHexList:[self.vividMacaronColors copy]];
    [pickerHeader addSubview:colorPickerView];
    [colorPickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_offset(0);
        make.height.mas_equalTo(22);
    }];
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleInsetGrouped];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = UIColor.clearColor;
    _tableView = tableView;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableHeaderView = pickerHeader;
    [self.tableView registerClass:[USInputCell class] forCellReuseIdentifier:@"USInputCellId"];
    [self.tableView registerClass:[USMemorialChangeStickerCell class] forCellReuseIdentifier:@"USMemorialChangeStickerCellId"];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.mas_equalTo(header.mas_bottom);
    }];
    
    [self.tableView reloadData];
    
    [self.view addSubview:self.stickerView];
    CGFloat stickerViewH = 324 + 12 + self.view.window.safeAreaInsets.bottom;
    [self.stickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.bottom.mas_offset(stickerViewH);
        make.height.mas_equalTo(stickerViewH);
    }];
    
}
- (NSMutableArray <NSString *>*)vividMacaronColors {
    if (_vividMacaronColors == nil) {
        NSArray<NSString *> *colors = @[
            // 🌸 粉红
            @"#E985A6", @"#E15A87",
            // 🔴 红
            @"#E98585", @"#E15A5A",
            // 🟠 橙
            @"#E9AF85", @"#E1925A",
            // 🟡 黄
            @"#E9D885", @"#E1CB5A",
            // 🟢 绿
            @"#96E985", @"#70E15A",
            // 🔵 蓝
            @"#85B7E9", @"#5A9EE1",
            // 🟦 青
            @"#85E9D8", @"#5AE1CB",
            // 🟣 紫
            @"#B785E9", @"#9E5AE1",
        ];
        _vividMacaronColors = [NSMutableArray arrayWithArray:colors];

    }
    return _vividMacaronColors;
}
- (USStickerPickerView *)stickerView {
    if (_stickerView == nil) {
        self.stickerView = [[USStickerPickerView alloc]initWithStickerShowCloseButton:YES andShowEmpty:YES];
        self.stickerView.delegate = self;
        self.stickerView.hidden = YES;
    }
    return _stickerView;
}

- (void)startUpload{
    [self.indicator startAnimating];
    UIBarButtonItem *loadingItem = [[UIBarButtonItem alloc] initWithCustomView:self.indicator];
    self.navigationItem.rightBarButtonItem = loadingItem;
    self.view.userInteractionEnabled = NO; // 禁用整个页面操作

    
}
- (void)endUpLoad{
    self.navigationItem.rightBarButtonItem = self.doneItem;
    [self.indicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}

- (void)doneAction:(id)sender{
    [super doneAction:sender];
    [USFeedbackTool impactSoft];
    
    [self startUpload];

    @weakify(self)
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"anniversaryDate"] = self.dayModel.anniversaryDate;
    params[@"anniversaryName"] = self.dayModel.anniversaryName;
    params[@"color"] = self.dayModel.color;
    params[@"coverUrl"] = self.dayModel.coverUrl;
    params[@"includeStart"] = self.dayModel.includeStart ? @"1":@"0";
    params[@"repeatYearly"] = self.dayModel.repeatYearly ? @"1":@"0";
    params[@"homePageFlag"] = self.dayModel.homePageFlag ? @"1":@"0";
 
    NSString *path = API_AnniversaryAdd;
    if (self.isEdit) {
        path = API_AnniversaryEdit;
        params[@"anniversaryId"] = self.dayModel.anniversaryId;
    }
    
    NSLog(@"params = %@",params);
    [[EMNetWork shareManager] em_post:path
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {

        @strongify(self)
        [self endUpLoad];
        if (!api.success) {
            return;
        }
        if (self.isEdit) {
            [self remindActionWithModel:self.dayModel];
            
            if (self.editSuccess) {
                self.editSuccess();
            }
        }else{
            USMemorialDayModel *model = [USMemorialDayModel mj_objectWithKeyValues:api.data[@"Anniversary"]];
            [self remindActionWithModel:model];
        }
        
        [USFeedbackTool notifySuccess];
        [self.navigationController popViewControllerAnimated:YES];
        
    } fail:^{
        
        [self endUpLoad];

    }];
    
    
}

#pragma mark - 提醒Ta
- (void)remindActionWithModel:(USMemorialDayModel *)model {
 
    NSString *action_title = [NSString stringWithFormat:@"%@添加了纪念日",USUser.user.nickname];
    NSDictionary *ext = @{@"action_id":model.anniversaryId?:@"",
                          @"action_title":action_title,
                          @"action_content":@"快来看看吧~"};
    
    [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_MemorialDay andExt:ext];

    [USIMCmdCustomManager imSendCustomWithEvent:USIMCmdAction_MemorialDay andCustomExt:ext];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@(USNoticeType_MemorialDay) forKey:@"type"];
    [param setValue:model.anniversaryId?:@"" forKey:@"pkId"];
    [param setValue:@"添加了纪念日" forKey:@"content"];
    [param setValue:USUser.user.relUser.userId forKey:@"userId"];
    [param setValue:@(1) forKey:@"shareSpaceFlag"];

    [[EMNetWork shareManager] em_post:NoticeAdd
                               params:param
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
    } fail:^{
        
        
    }];
}

#pragma mark SelectAction
- (void)selectTipAlert {
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"每年重复不能包含起始日" detailTitle:nil contentView:nil leftButtonImageName:@" " rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
     [alert show];
}

#pragma mark action
- (void)modifyStickerAction{
    [USFeedbackTool impactMedium];
    
    [self.view endEditing:YES];
    [self.stickerView showStickerPickerWithAllowTapDismiss:YES];
}

- (void)chooseDateAction{
    [USFeedbackTool impactMedium];
    
    [self.view endEditing:YES];

    NSDate *date = [NSDate date];
    if (self.dayModel.anniversaryDate.length > 0) {
        date = [NSDate dateWithTimeIntervalSince1970:[self.dayModel.anniversaryDate integerValue]];
    }
    USDateAlertView *alert = [[USDateAlertView alloc]initWithDate:date andSubTitle:@"设置纪念日日期" limitToNow:self.dayModel.togetherFlag ? YES : NO];
    [alert showInView:UIViewController.topViewController.view];
    @weakify(self)
    alert.didChooseBlock = ^(NSDate * _Nonnull date) {
        @strongify(self)

        NSTimeInterval timestamp = [date timeIntervalSince1970];
        NSInteger timestampInSeconds = (NSInteger)timestamp;
     
        self.dayModel.anniversaryDate = [NSString stringWithFormat:@"%li",timestampInSeconds];
        self.dayView.dayModel = self.dayModel;

        [self.tableView reloadData];
    };
}

#pragma mark USStickerPickerViewDelegate
- (void)stickerPickerView:(USStickerPickerView *)picker didSelectSticker:(USStickerModel *)sticker{
    self.dayModel.coverUrl = sticker.name;
    self.dayView.cover = sticker.name;
    [self.tableView reloadData];

}
- (void)stickerPickerViewDidSelectEmpty {
    self.dayModel.coverUrl = @"";
    self.dayView.cover = @"";
    [self.tableView reloadData];

}

#pragma mark - <UITableViewDataSource,UITableViewDelegate>

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    DTItem *item = self.list[indexPath.section].items[indexPath.row];
    if ([item.identifier isEqualToString:@"modifySticker"]) {
        [self modifyStickerAction];
    }else if ([item.identifier isEqualToString:@"date"]){
        [self chooseDateAction];
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.list.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.list[section].items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [UITableViewCell us_defaultCell];
    
    DTItem *item = self.list[indexPath.section].items[indexPath.row];
    
    cell.imageView.image = item.image;
    
    cell.textLabel.text = item.title;
    
    cell.textLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    
    cell.backgroundColor = [UIColor mi_1_color];
    
    if ([item.identifier isEqualToString:@"modifySticker"]) {
        
        USMemorialChangeStickerCell *s_cell = [tableView dequeueReusableCellWithIdentifier:@"USMemorialChangeStickerCellId"];
        cell = s_cell;
        cell.textLabel.text = item.title;
        cell.imageView.image = item.image;
        [cell us_setDefaultArrow];
        if (self.dayModel.coverUrl.length > 0) {
            s_cell.rightImageView.image = [UIImage imageNamed:self.dayModel.coverUrl];
        }else{
            s_cell.rightImageView.tintColor = [UIColor jk_colorWithHexString:self.dayModel.color];
            s_cell.rightImageView.image = [[UIImage systemImageNamed:@"circle.fill"] imageWithTintColor:[UIColor jk_colorWithHexString:self.dayModel.color]];
        }
        
    }else if ([item.identifier isEqualToString:@"memorialName"]){
        
        USInputCell * tf_cell = [tableView dequeueReusableCellWithIdentifier:@"USInputCellId"];
        tf_cell.inputField.placeholder = @"请输入";
        cell = tf_cell;
        [tf_cell configureWithTitle:item.title image:item.image inputText: self.dayModel.anniversaryName];

        @weakify(self);
        [[tf_cell.inputField.rac_textSignal distinctUntilChanged] subscribeNext:^(NSString * _Nullable text) {
            @strongify(self);
            // 限制最多20字符
            if (text.length > 20) {
                text = [text substringToIndex:20];
                tf_cell.inputField.text = text;
            }
            self.dayModel.anniversaryName = text;
            self.dayView.dayModel = self.dayModel;
        }];
   
    }else if ([item.identifier isEqualToString:@"date"]){
        
        if (self.dayModel.anniversaryDate.length > 0) {
            cell.detailTextLabel.text =  self.dayModel.dayDescription;
        }else{
            cell.detailTextLabel.text = @"请选择";
        }
        [cell us_setDefaultArrow];
        
    }else if ([item.identifier isEqualToString:@"includeStartDate"]){
        
        [cell us_setAccessorySwitchIsSelected:self.dayModel.includeStart allowToggle:!self.dayModel.repeatYearly action:^(BOOL selected) {
            self.dayModel.includeStart = selected;
            self.dayView.dayModel = self.dayModel;
        } disabledAction:^{
            
            [self selectTipAlert];
        }];
    }else if ([item.identifier isEqualToString:@"repeatYearly"]){
 
        [cell us_setAccessorySwitchisSelected:self.dayModel.repeatYearly action:^(BOOL selected) {
            //每年重复则不能包含起始日
            self.dayModel.repeatYearly = selected;
            self.dayView.dayModel = self.dayModel;
            
            self.dayModel.includeStart = NO;
            [self.tableView reloadData];
        }];
    }else if ([item.identifier isEqualToString:@"pinTop"]){
        [cell us_setAccessorySwitchisSelected:self.dayModel.homePageFlag action:^(BOOL selected) {
            self.dayModel.homePageFlag = selected;
        }];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 68;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 16;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return .1;
}


@end
